package com.lance.answer.gui.answer.gk.answer.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.AnswerDTO;
import com.lance.answer.question_answer.tmp.QuestionAnswerCreateTopic;
import com.lance.answer.util.Constant;
import com.lance.answer.util.HttpClientUtil;
import com.lance.answer.util.MD5Utils;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CreateTopicTask extends Thread {


    private final String driverPath;
    private final LinkedBlockingDeque<AnswerDTO> answerDTOS;

    public CreateTopicTask(String driverPath, LinkedBlockingDeque<AnswerDTO> answerDTOS) {
        this.driverPath = driverPath;
        this.answerDTOS = answerDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (answerDTOS.size() > 0) {
            AnswerDTO answerDTO = answerDTOS.take();
            String userName = answerDTO.getUsername();
            String password = answerDTO.getPwd();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), answerDTOS.size(), userName, password);
            run(driverPath, answerDTO);
            //todo
        }

        if (answerDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }




    // 管理学基础 2065001457555 19940419
    public static void run(String driverPath,AnswerDTO answerDTO) throws Exception {
        WebDriver driver = Util.getDriver(driverPath);
        //String url = "http://student.ouchn.cn/";
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(3000);
        String userName = answerDTO.getUsername();
        String password = answerDTO.getPwd();
        String subjectName = answerDTO.getSubjectName();
        List<String> urlTasks = answerDTO.getTopicUrl();
        //Util.login(driver, "2065001457555", "19940419");
        Util.login(driver, userName, password);
        Util.switchToFirst(driver);
        Thread.sleep(3000);
        // 形考作业的链接 管理学
        //List<String> urlTasks = Util.getCourseTaskUrl(driver, CourseTypeEnum.BasicManagement.name);
        //List<String> urlTasks = Util.getCourseTaskUrl(subjectCode);

        //chromeDriver.navigate().refresh();
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            Util.switchToFirst(driver);
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

            if (!mediaTitle.contains(subjectName)) {
                continue;
            }
            //点击进入学习的按钮
            WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
            studyButton.click();
            //Util.switchToLast(driver);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(urlTasks.toString());
        for (String urlTask : urlTasks) {
            // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
            driver.get(urlTask);
            Thread.sleep(2 * 1000);
            // 点击继续作业


            try {
                String content = driver.findElement(By.id("intro")).getText();
                content = content.trim();
                content = DealJsonString.removeSpace(content);
                createTopic(driver, content.substring(0, content.length() > 20 ? 20 : content.length() / 2), content);
            } catch (Exception e) {
                try {
                    WebElement doWorkArea = driver.findElement(By.cssSelector("*[class='btn btn-primary']"));
                    doWorkArea.click();


                    String title  = "网上课堂案例讨论";
                    try {
                        WebElement my = driver.findElement(By.cssSelector("span[class='usertext mr-1']"));
                        title = title+"-"+my.getText();
                    }catch (Exception e1111){

                    }
                    String answer = "且不管前路如何，今天有阳光，那么我们就拥抱温暖；当风雨来临的时候，我们已经储备了迎接寒冷的能量。";

                    driver.findElement(By.id("id_subject")).sendKeys(title);
                    Thread.sleep(2000);
                    WebElement iframe = driver.findElement(By.id("id_message_ifr"));
                    String js = "document.getElementById('"+iframe.getAttribute("id")+"').contentWindow.document.body.innerText = '"+answer+"'";
                    System.err.println(js);
                    ((JavascriptExecutor)driver).executeScript(js);
                    //  Thread.sleep(200000);
                    driver.findElement(By.id("id_submitbutton")).click();
                } catch (Exception e11) {
                    System.err.println("taskUrl:" + urlTask + "  occur error");
                    e11.printStackTrace();
                    Thread.sleep(2000);
                }
            }


            //回到试题首页
            TimeUnit.SECONDS.sleep(3);
        }

        Thread.sleep(2000);
        driver.close();
        driver.quit();
    }

    public static void createTopic(WebDriver driver, String title, String answer) {
        try {
            WebElement doWorkArea = driver.findElement(By.cssSelector("*[class='btn btn-primary']"));
            doWorkArea.click();

            try {
                WebElement my = driver.findElement(By.cssSelector("span[class='usertext mr-1']"));
                title = title + "-" + my.getText();
            } catch (Exception e) {

            }
            driver.findElement(By.id("id_subject")).sendKeys(title);
            Thread.sleep(2000);
            WebElement iframe = driver.findElement(By.id("id_message_ifr"));
            String js = "document.getElementById('" + iframe.getAttribute("id") + "').contentWindow.document.body.innerText = '" + answer + "'";
            System.err.println(js);
            ((JavascriptExecutor) driver).executeScript(js);
            //  Thread.sleep(200000);
            driver.findElement(By.id("id_submitbutton")).click();
        } catch (Exception e) {
        }
    }




    @Data
    static class TopicInfo{
        String url;
        String title;
        String content;

        public TopicInfo(String url, String title, String content) {
            this.url = url;
            this.title = title;
            this.content = content;
        }
        public TopicInfo(){

        }
    }




    private static void closeDriver(WebDriver driver) {
        try {
            driver.close();
            driver.quit();
        } catch (Exception e) {

        }
    }

}
